﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections.Specialized;
using Distrackting.DataLayer;
using Distrackting.BusinessLayer;

namespace Distrackting.BusinessLayer
{

    public class DMembershipProvider : SqlMembershipProvider
    {
        public string EncryptString(string str)
        {
            return Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(str)));
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, Object providerUserKey, out MembershipCreateStatus status)
        {
            // validar regras de password
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(email, password, true);
            OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            // criar o user
            MembershipUser mu = GetUser(email, false);
            if (mu == null)
            {
                Utilizador u = new Utilizador();
                u.email = email;
                u.password = EncryptString(password);
                u.data_ultimo_login = DateTime.Now;
                u.nome = HttpContext.Current.Session["CU_nome"].ToString();
                u.cod_localidade = new Guid(HttpContext.Current.Session["CU_cod_loc"].ToString());
                u.data_nascimento = Convert.ToDateTime(HttpContext.Current.Session["CU_data_nasc"].ToString());
                u.numero_telemovel = HttpContext.Current.Session["CU_telemovel"].ToString();
                u.sexo = Convert.ToChar(HttpContext.Current.Session["CU_sexo"]);
                u.cod_nivel = new Guid("adf0403a-ea0c-40d3-8436-290c76640c54");
                u.aprovado = true;
                u.bloqueado = false;
                try
                {
                    Guid newUser = dataUtilizador.createUtilizador(u); 
                    if (newUser == Guid.Empty) status = MembershipCreateStatus.UserRejected;
                    else status = MembershipCreateStatus.Success;

                    return GetUser(newUser, false);
                }
                catch (Exception e) { throw e; }

              
            }
            else
            {
                status = MembershipCreateStatus.DuplicateEmail;
            }
            return null;
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            //TODO verficiar o u.approved
            try
            {
                Utilizador u = GerirUtilizadores.getUtilizador(username);

                MembershipUser mu = new MembershipUser(
                                                    this.Name,
                                                    u.email,
                                                    u.cod_utilizador,
                                                    u.email,
                                                    "",
                                                    "",
                                                    Convert.ToBoolean(u.aprovado),
                                                    Convert.ToBoolean(u.bloqueado),
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login));

                return mu;
            }
            catch (Exception)
            {

                return null;
            }
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            //TODO verficiar o u.approved
            try
            {
                Utilizador u = dataUtilizador.getUtilizador(new Guid((string)providerUserKey));

                MembershipUser mu = new MembershipUser(this.Name,
                                                    u.email,
                                                    u.cod_utilizador,
                                                    u.email,
                                                    "",
                                                    "",
                                                    true,
                                                    false,
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login),
                                                    Convert.ToDateTime(u.data_ultimo_login));

                return mu;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public override bool ValidateUser(string username, string password)
        {
            try
            {
                String encryptedPassword = EncryptString(password);
                Utilizador u = GerirUtilizadores.getUtilizador(username);
                Boolean approved = true;


                return ((u.password.Equals(encryptedPassword)) && (approved == true));
            }
            catch (Exception)
            {
                return false;
            }
        }


        public override bool ChangePassword(string username, string oldPwd, string newPwd)
        {
            if (!ValidateUser(username, oldPwd))
                return false;

            // verificar que a password segue as regras
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPwd, false);
            OnValidatingPassword(args);
            if (args.Cancel)
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Change password canceled due to new password validation failure.");


            // alterar a password
            Utilizador u = GerirUtilizadores.getUtilizador(username);
            if (u != null)
            {
                u.password = EncryptString(newPwd);
                return GerirUtilizadores.changeUtilizador(u);
            }

            return false;
        }
    }
}

